(import
 (except (rnrs base) let-values map)
 (only (guile)
       lambda* λ)
 (prerequisites))

;;; ========
;;; SCRAMBLE
;;; ========

;; The book defines a mysterious function named ~scramble~ and asks
;; the reader to figure out, what it does.

(define scramble
  (λ (tup)
    (scramble-b tup '())))

(define scramble-b
  (λ (tup rev-pre)
    (cond
     [(null? tup) '()]
     [else
      (cons
       (pick (car tup)
             ;; Here we artificially make the reversed prefix longer by the
             ;; current element, so that pick will pick the correct element.
             (cons (car tup) rev-pre))
       (scramble-b (cdr tup)
                   ;; We add the current element to the reversed prefix of the
                   ;; next iteration.
                   (cons (car tup) rev-pre)))])))

;; EXPLANATION: The ~scramble~ function looks at each number in the
;; tuple. The number at each position (position = index + 1, or
;; "distance from the start of the list") is substracted from its
;; position and the resulting value is the index of the value, which
;; shall be the final result for the number in the resulting tuple.

;; USAGE: Let us try it:

(display
 (simple-format
  #f "(scramble '(1 2 3 1 2 3 4 1 8 2 10)) -> ~a\n"
  (scramble '(1 2 3 1 2 3 4 1 8 2 10))))
